package de.snom;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.widgets.Shell;

import com.google.gdata.util.common.util.Base64;

import de.snom.HttpDailer.Command;

public class HttpDailer implements Runnable {
	
	public enum Command{DAIL, CANCEL }

	private String number;
	private final Command command;
	private final Shell shell;

	public HttpDailer(String number,Command command,Shell shell) {

		
	this.command = command;
	this.shell = shell;
	if (Command.DAIL == command) {
		this.number = cleanNumber(number);
	}	
	}

	public HttpDailer(Command command,Shell shell) {
		this.command = command;
		// TODO Auto-generated constructor stub
		this.shell = shell;
	}

	private String cleanNumber(String number) {
		
		number = number.replaceAll("\\(0\\)", "");
		number = number.replaceAll("\\+", "00");
		number = number.replaceAll("[^0-9]", "");
		
		return number;
	}

	@Override
	public void run() {
		PhoneData phoneData = PhoneData.get();
		switch (this.command) {
		case DAIL:
			 sendGetRequest("http://"+phoneData.getPhoneURLString()+"/command.htm?number="
					+ number,PhoneData.get().getPhoneUserNameString()+":"+PhoneData.get().getPhonePasswordString());
			
			break;
			
		case CANCEL:
			 String sendGetRequest = sendGetRequest("http://"+phoneData.getPhoneURLString()+"/command.htm?key=CANCEL",PhoneData.get().getPhoneUserNameString()+":"+PhoneData.get().getPhonePasswordString());
			System.out.println(sendGetRequest);
			 break;

		default:
			break;
		}
		
		

	}

	public  String sendGetRequest(String urlString, String userPassword) {
		String result = null;
		try {
			if (urlString.startsWith("http://")) {
				// Send a GET request to the servlet

				URL url = new URL(urlString);
				String encoding = Base64.encode(userPassword.getBytes());
				URLConnection connection = url.openConnection();
				connection.setRequestProperty ("Authorization", "Basic " + encoding);				
				connection.setReadTimeout(1000);
				connection.setConnectTimeout(1000);

				// Get the response
				BufferedReader rd = new BufferedReader(new InputStreamReader(
						connection.getInputStream()));
				StringBuffer sb = new StringBuffer();
				String line;
				while ((line = rd.readLine()) != null) {
					sb.append(line);
				}
				rd.close();
				result = sb.toString();

			}
		} catch (Exception e) {
			shell.getDisplay().asyncExec(new Runnable() {
				
				@Override
				public void run() {
					ErrorDialog.openError(shell,  "error", "http call failed", new Status(IStatus.ERROR, "My Plug-in ID", 0,
				            "Maybe you entered something wrong or you have no connection to your phone - Dude", null)) ;
				}
			});
			e.printStackTrace();
		}
		return result;
	}
}
